﻿using LinqToLfsWorld.Interface;
using LinqToLfsWorld.Serialization;

namespace LinqToLfsWorld.Extensions
{
	/// <summary>
	/// A collection of extension methods used for serialization.
	/// </summary>
	public static class SerializationExtensions
	{

		/// <summary>
		/// Serializes an entity to a JSON-formatted string.
		/// </summary>
		/// <param name="entity">The entity.</param>
		public static string ToJson(this ILfsWorldEntity entity)
		{
			JsonSerializer<ILfsWorldEntity> serializer = new JsonSerializer<ILfsWorldEntity>();
			return serializer.Serialize(entity);
		}

		/// <summary>
		/// Deserializes an entity from a JSON-formatted string.
		/// </summary>
		///<param name="serialized">The string containing the serialized entity in JSON format.</param>
		///<typeparam name="T">The entity type to serialize to.</typeparam>
		public static T EntityFromJson<T>(this string serialized)
			where T: class, ILfsWorldEntity
		{
			JsonSerializer<T> serializer = new JsonSerializer<T>();
			return serializer.Deserialize(serialized);
		}

		/// <summary>
		/// Serializes an entity to Xml
		/// </summary>
		/// <param name="entity">The entity.</param>
		/// <returns>The entity serialized to string containing some xml</returns>
		public static string ToXml(this ILfsWorldEntity entity)
		{
			XmlSerializer<ILfsWorldEntity> serializer = new XmlSerializer<ILfsWorldEntity>();
			return serializer.Serialize(entity);
		}

		/// <summary>
		/// Deserializes an entity from a string containing some xml.
		/// </summary>
		/// <typeparam name="T">The type contained in the serialized xml</typeparam>
		/// <param name="serialized">The serialized xml string.</param>
		/// <returns>An instance of the entity which has been deserialized from the xml string.</returns>
		public static T EntityFromXml<T>(this string serialized)
			where T : class, ILfsWorldEntity
		{
			XmlSerializer<T> serializer = new XmlSerializer<T>();
			return serializer.Deserialize(serialized);
		}
	}
}
